package guoanmaker.operator.business.service;

import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.Date;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import guoanmaker.operator.business.model.OperatorActivityEnlist;
import guoanmaker.operator.business.model.OperatorEventDetails;
import guoanmaker.operator.business.model.PayInfo;
import guoanmaker.operator.business.model.PersonalUserCoupon;
import guoanmaker.operator.business.modelnobind.OpersonalUUC;
import guoanmaker.operator.business.modelnobind.operatorEnlistDetails;
import guoanmaker.operator.business.repository.OperatorActivityEnlistRepository;
import guoanmaker.operator.business.repository.OperatorCouponsRepository;
import guoanmaker.operator.business.repository.OperatorEventDetailsRepository;
import guoanmaker.operator.business.repository.PersonalUserCouponRepository;
import guoanmaker.operator.helper.common.util.PayAnaiyInfor;
import guoanmaker.operator.helper.common.util.sendCode;

/**
 * @author wanghongwei 
 * @ClassName: OperatorActivityEnlistService 
 * @Description: OperatorActivityEnlistService
 * @date 2017/8/11
 */
@Service
public class OperatorActivityEnlistService implements OperatorActivityEnlistServiceInterface {
	private final OperatorActivityEnlistRepository operatorActivityEnlistRepository;
	private final OperatorEventDetailsRepository operatorEventDetailsRepository;
	private final PersonalUserCouponRepository personalUserCouponRepository;
	private final OperatorCouponsRepository operatorCouponsRepository;
	@PersistenceContext
	private EntityManager manager;

	public OperatorActivityEnlistService(OperatorActivityEnlistRepository operatorActivityEnlistRepository,
			OperatorEventDetailsRepository operatorEventDetailsRepository,
			PersonalUserCouponRepository personalUserCouponRepository,
			OperatorCouponsRepository operatorCouponsRepository) {
		this.operatorActivityEnlistRepository = operatorActivityEnlistRepository;
		this.operatorEventDetailsRepository = operatorEventDetailsRepository;
		this.personalUserCouponRepository = personalUserCouponRepository;
		this.operatorCouponsRepository = operatorCouponsRepository;
	}

	@Transactional
	@Override
	public OperatorActivityEnlist saveActivityEnlist(OperatorActivityEnlist operatorActivityEnlist) {
		if (operatorActivityEnlist.getId() != null) {
			return null;
		}
		Date date = new Date();
		OperatorActivityEnlist ActivityEnlist = new OperatorActivityEnlist();
		OperatorEventDetails operatorEventDetails = operatorEventDetailsRepository
				.findOne(operatorActivityEnlist.getActivityId());
		int count = operatorActivityEnlistRepository.queryCountByUserIdAndActivity(operatorActivityEnlist.getUserId(),
				operatorActivityEnlist.getActivityId());
		if (operatorEventDetails.getIsMoney() != null && operatorEventDetails.getIsMoney() == 1) {// 收费
			if (count >= operatorEventDetails.getUnitNum()) {
				ActivityEnlist.setId("-104");
				return ActivityEnlist;
			}
			if (operatorEventDetails.getEnrollment()!=0 && operatorEventDetails.getEventJoinPersonNum() + operatorActivityEnlist.getBuyNum() > operatorEventDetails
					.getEnrollment()) {
				ActivityEnlist.setId("-105");
				return ActivityEnlist;
			}
		}
		if (operatorEventDetails.getIsMoney() != null && operatorEventDetails.getIsMoney() == 0) {// 不收费
			if (count >= 1) {
				ActivityEnlist.setId("-104");
				return ActivityEnlist;
			}
		}
		Long StartTime = operatorEventDetails.getSignupStartTime().getTime();
		Long EndTime = operatorEventDetails.getSignupEndTime().getTime();
		if (StartTime <= date.getTime() && date.getTime() <= EndTime) {// 判断活动报名时间
			// 判断 活动人数
			if (operatorEventDetails.getEnrollment() == 0) {// 无限制
				// IsMoney 0不收费 1收费
				// 订单状态Status 0 未支付 1 已支付 2 取消报名
				if (operatorEventDetails.getIsMoney() == 0) {
					
					operatorActivityEnlist.setState(1);// 报名成功
					operatorEventDetailsRepository.updateEnrollmentAdd(operatorActivityEnlist.getActivityId());
					//发送短信息
					try {
						sendCode.sendMessage(operatorActivityEnlist.getTelePhone(),"尊敬的客户您好，您已成功报名"+operatorEventDetails.getEventTitle()+"活动，感谢您的参与，谢谢！客服热线：4008518585");
					} catch (Exception e) {
						e.printStackTrace();
					}
					
				} else {
					// 金额校验
					Double price = (double) (operatorEventDetails.getUnitPrice() * 100
							* operatorActivityEnlist.getBuyNum());
					Double payprice = operatorActivityEnlist.getPayMoney() * 100;
					if (price.equals(payprice) == false) {
						ActivityEnlist.setId("-102");
						return ActivityEnlist;
					}
					// 修改活动报名人数
					operatorEventDetailsRepository.updateEnrollmentBuyNumAdd(operatorActivityEnlist.getActivityId(),
							operatorActivityEnlist.getBuyNum());
					operatorActivityEnlist.setState(0);// 待支付
				}
				operatorActivityEnlist.setBuildTime(new Date());
				OperatorActivityEnlist activityEnlist = operatorActivityEnlistRepository.save(operatorActivityEnlist);
				return activityEnlist;

			}
			if (operatorEventDetails.getEventJoinPersonNum() < operatorEventDetails.getEnrollment()
					&& operatorEventDetails.getEnrollment() != 0) {
				// IsMoney 0不收费 1收费
				// 订单状态Status 0 未支付 1 已支付 2 取消报名
				if (operatorEventDetails.getIsMoney() == 0) {
					operatorActivityEnlist.setState(1);// 报名成功
					operatorEventDetailsRepository.updateEnrollmentAdd(operatorActivityEnlist.getActivityId());
					//发送短信息
					try {
						sendCode.sendMessage(operatorActivityEnlist.getTelePhone(),"尊敬的客户您好，您已成功报名"+operatorEventDetails.getEventTitle()+"活动，感谢您的参与，谢谢！客服热线：4008518585");
					} catch (Exception e) {
						e.printStackTrace();
					}
				} else {
					// 金额校验
					Double price = (double) (operatorEventDetails.getUnitPrice() * 100
							* operatorActivityEnlist.getBuyNum());
					Double payprice = operatorActivityEnlist.getPayMoney() * 100;
					if (price.equals(payprice) == false) {
						ActivityEnlist.setId("-102");
						return ActivityEnlist;
					}
					// 修改活动报名人数
					operatorEventDetailsRepository.updateEnrollmentBuyNumAdd(operatorActivityEnlist.getActivityId(),
							operatorActivityEnlist.getBuyNum());
					operatorActivityEnlist.setState(0);// 待支付
				}
				operatorActivityEnlist.setBuildTime(new Date());
				OperatorActivityEnlist activityEnlist = operatorActivityEnlistRepository.save(operatorActivityEnlist);
				return activityEnlist;
			}
			ActivityEnlist.setId("-101");
			return ActivityEnlist;
		}
		return null;
	}

	@Override
	public Object getActivityEnlist(String Id) {
		if (Id != null) {
			String sql = "SELECT b.event_title,b.is_money, b.event_pic_url,b.organizer,b.event_start_time,c.name as  place_name ,"
					+ "d.name as  city_name,b.event_detailed_address,b.event_end_time,a.user_id,a.activity_id,a.link_man,"
					+ "a.tele_phone,a.buy_num,a.pay_money,a.company_name,a.state,a.stream_num,a.build_time,a.id FROM"
					+ " t_operator_activity_enlist a ,t_operator_event_details b LEFT JOIN t_provide_province  c on b.event_place=c.id LEFT JOIN t_provide_city d on b.event_county =d.id WHERE a.id=:id and a.activity_id=b.id";
			Query query = manager.createNativeQuery(sql, operatorEnlistDetails.class);
			query.setParameter("id", Id);
			List<operatorEnlistDetails> enlist = (List<operatorEnlistDetails>) query.getResultList();
			return enlist.get(0);
		}
		return null;
	}

	@Override
	public void deleteActivityEnlistById(String id) {
		operatorActivityEnlistRepository.delete(id);
	}

	@Transactional
	@Override
	public int updateActivityEnlistState(OperatorActivityEnlist operatorActivityEnlist) throws Exception {
		Date date = new Date();
		OperatorActivityEnlist enlist = operatorActivityEnlistRepository.getOne(operatorActivityEnlist.getId());
		String activityId = enlist.getActivityId();
		OperatorEventDetails operatorEventDetails = operatorEventDetailsRepository.findOne(activityId);
		Long signupEndtime = operatorEventDetails.getSignupEndTime().getTime();
		int count = 0;
		if (date.getTime() < signupEndtime) {
			Integer state = operatorActivityEnlist.getState();
			String id = operatorActivityEnlist.getId();
			int orgState = -1;
			if (state == 2) {// 取消
				orgState = 0;
			}
			count = operatorActivityEnlistRepository.updateActivityEnlistState(state, orgState, id);
			if (count == 0) {
				throw new Exception("数据修改失败");
			}
			operatorEventDetailsRepository.updateEnrollmentRemove(operatorActivityEnlist.getActivityId(),
					operatorActivityEnlist.getBuyNum());
		}
		return count;
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<operatorEnlistDetails> getFenYeEnlistAll(String userId, Integer page, Integer size) {
		String sql = "SELECT b.event_title,b.is_money, b.event_pic_url,b.organizer,b.event_start_time,c.name as  place_name ,"
				+ "d.name as  city_name,b.event_detailed_address,b.event_end_time,a.user_id,a.activity_id,a.link_man,"
				+ "a.tele_phone,a.buy_num,a.pay_money,a.company_name,a.state,a.stream_num,a.build_time,a.id  FROM"
				+ " t_operator_activity_enlist a ,t_operator_event_details b LEFT JOIN t_provide_province  c on b.event_place=c.id LEFT JOIN t_provide_city d on b.event_county =d.id WHERE a.user_id=:userId and a.activity_id=b.id ORDER BY a.build_time DESC";
		Query query = manager.createNativeQuery(sql, operatorEnlistDetails.class);
		int index = (page - 1) * size;
		List<operatorEnlistDetails> enlist = (List<operatorEnlistDetails>) query.setParameter("userId", userId)
				.setMaxResults(size).setFirstResult(index).getResultList();
		return enlist;

	}

	@SuppressWarnings("unchecked")
	@Override
	public OperatorActivityEnlist getFenYeEnlistAndCount(String userId, Integer page, Integer size) {
		Integer count = operatorActivityEnlistRepository.queryCountByUserId(userId);
		OperatorActivityEnlist operatorActivityEnlist = new OperatorActivityEnlist();
		operatorActivityEnlist.setCount(count);
		String sql = "SELECT b.event_title,b.is_money, b.event_pic_url,b.organizer,b.event_start_time,c.name as  place_name ,"
				+ "d.name as  city_name,b.event_detailed_address,b.event_end_time,a.user_id,a.activity_id,a.link_man,"
				+ "a.tele_phone,a.buy_num,a.pay_money,a.company_name,a.state,a.stream_num,a.build_time,a.id FROM"
				+ " t_operator_activity_enlist a ,t_operator_event_details b LEFT JOIN t_provide_province  c on b.event_place=c.id LEFT JOIN t_provide_city d on b.event_county =d.id WHERE a.user_id=:userId and a.activity_id=b.id ORDER BY a.build_time DESC";
		Query query = manager.createNativeQuery(sql, operatorEnlistDetails.class);
		int index = (page - 1) * size;
		List<operatorEnlistDetails> enlist = (List<operatorEnlistDetails>) query.setParameter("userId", userId)
				.setMaxResults(size).setFirstResult(index).getResultList();
		operatorActivityEnlist.setEnlistlist(enlist);
		return operatorActivityEnlist;
	}

	@Transactional
	@SuppressWarnings("unused")
	@Override
	public int validateActivityEnlistCoupons(OperatorActivityEnlist operatorActivityEnlist) {
		String couponId = operatorActivityEnlist.getCouponId();// 商品优惠券id
		String id = operatorActivityEnlist.getId();// 订单id
		if (couponId == null || couponId.equals("") == true) {
			Double couponPrice = null;
			operatorActivityEnlistRepository.updateCouponIdAndPrice(id, couponId, couponPrice);
			return 1;
		}
		OperatorActivityEnlist enlist = operatorActivityEnlistRepository.getOne(id);
		String userId = enlist.getUserId();
		String jpql = "select new guoanmaker.operator.business.modelnobind.OpersonalUUC(b.id,b.isUsed,b.ocId,"
				+ "b.userId,a.couponstype,a.fullamount,a.subamount) "
				+ " from PersonalUserCoupon b,OperatorCoupons a  where b.id=:couponId and b.userId=:userId and a.id=b.ocId";
		Query query = manager.createQuery(jpql);
		query.setParameter("couponId", couponId);
		query.setParameter("userId", userId);
		OpersonalUUC enlistCoupons = (OpersonalUUC) query.getSingleResult();
		manager.clear();
		if (enlistCoupons.getFullamount() <= enlist.getPayMoney()) {// 支付金额大于等于优惠券
			operatorActivityEnlistRepository.updateCouponIdAndPrice(id, couponId, enlistCoupons.getSubamount());
			return 0;
		}
		return 2;
	}

	@Transactional
	@Override
	public int saveStreamNum(OperatorActivityEnlist operatorActivityEnlist) {
		Integer count = operatorActivityEnlistRepository.updateStreamNum(operatorActivityEnlist.getId(),
				operatorActivityEnlist.getStreamNum());
		return count;
	}

	/**
	 * 发起支付接口
	 */
	@Override
	public PayInfo paymentActivityEnlist(String id, String channel, String back_url) {
		PayInfo payinfor = new PayInfo();
		OperatorActivityEnlist activityEnlist = operatorActivityEnlistRepository.findOne(id);
		String uid = activityEnlist.getUserId();// 用户id
		String systemCode = "10";// 平台账号
		String platOrderId = id;// 业务平台订单号
		String backUrl = null;
		try {
			backUrl = URLEncoder.encode(back_url, "utf-8");
		} catch (UnsupportedEncodingException e1) {
			e1.printStackTrace();
		}

		// 支付金额
		int amount = Integer.parseInt((activityEnlist.getPayMoney() * 100 + "").substring(0,
				(activityEnlist.getPayMoney() * 100 + "").indexOf(".")));
		Integer card_type = null;
		Integer card_amount = null;
		if (activityEnlist.getCouponId() != null) {// 使用优惠券
			card_type = 1;// 使用优惠券类型 1平台优惠券
			// 优惠券金额：分
			card_amount = Integer.parseInt((activityEnlist.getPayMoney() * 100 + "").substring(0,
					(activityEnlist.getPayMoney() * 100 + "").indexOf(".")));
		}
		if (activityEnlist.getCouponId() == null) {
			card_type = 0;// 使用优惠券类型 0不使用
			card_amount = 0; // 优惠券金额：分
		}
		Integer express_fee = 0;// 快递费金额：分
		String originalId = "00000000000000000000000000000001";// 平台服务商编号
		String companyName = "国安创客";// 服务商名称
		String companyTitle = "国安创客";// 服务商公司名称
		Integer isJava = 1;// 是否来自java新平台，1是 0否
		try {
			URL url = new URL("http://123.56.48.63/pay/original/pay.php?uid=" + uid + "&systemCode=" + systemCode
					+ "&platOrderId=" + platOrderId + "&channel=" + channel + "&amount=" + amount + "&card_type="
					+ card_type + "&card_amount=" + card_amount + "&express_fee=" + express_fee + "&originalId="
					+ originalId + "&companyName=" + companyName + "&companyTitle=" + companyTitle + "&back_url="
					+ backUrl + "&isJava=" + isJava + "");
			HttpURLConnection conn = (HttpURLConnection) url.openConnection();
			conn.setDoInput(true);
			conn.setDoOutput(true);
			conn.setRequestMethod("POST");
			conn.setAllowUserInteraction(false);
			conn.setUseCaches(false);
			InputStream input = conn.getInputStream();
			int resLen = 0;
			byte[] res = new byte[1024];
			StringBuilder sb = new StringBuilder();
			while ((resLen = input.read(res)) != -1) {
				sb.append(new String(res, 0, resLen));
			}
			String jsonStr = sb.toString();
			PayAnaiyInfor pay = new PayAnaiyInfor();
			payinfor = pay.getPayInfo(jsonStr, channel);
			operatorActivityEnlistRepository.updateStreamNum(id, payinfor.getId());
		} catch (MalformedURLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return payinfor;
	}

	@Override
	@Transactional
	public int updateEnlistPayState(String id, String streamNum) {
		OperatorActivityEnlist enlist = operatorActivityEnlistRepository.findOne(id);
		if(enlist.getState()==1){//如果该订单已支付跳出
			return 101;
		}
		Integer count = null;
		try {
			URL url = new URL("http://123.56.48.63/pay/original/retrieve.php?pingId=" + streamNum + "");
			HttpURLConnection conn = (HttpURLConnection) url.openConnection();
			conn.setDoInput(true);
			conn.setDoOutput(true);
			conn.setRequestMethod("POST");
			conn.setAllowUserInteraction(false);
			conn.setUseCaches(false);
			InputStream input = conn.getInputStream();
			int resLen = 0;
			byte[] res = new byte[1024];
			StringBuilder sb = new StringBuilder();
			while ((resLen = input.read(res)) != -1) {
				sb.append(new String(res, 0, resLen));
			}
			String jsonStr = sb.toString();
			if (jsonStr.equals("1") == true) {
				Integer orgState = 0;
				Integer state = 1;
				count = operatorActivityEnlistRepository.updateActivityEnlistState(state, orgState, id);// 订单
				
				 // 支付
				OperatorEventDetails operatorEventDetails = operatorEventDetailsRepository
						.findOne(enlist.getActivityId());
				//发送短信息
				try {
					sendCode.sendMessage(enlist.getTelePhone(),"尊敬的客户您好，您已成功报名"+operatorEventDetails.getEventTitle()+"活动，感谢您的参与，谢谢！客服热线：4008518585");
				} catch (Exception e) {
					e.printStackTrace();
				}
				if (enlist.getCouponId() != null) {
					PersonalUserCoupon personalUserCoupon = personalUserCouponRepository.findOne(enlist.getCouponId());
					personalUserCouponRepository.updateIsUsedByid(enlist.getCouponId());
					operatorCouponsRepository.updateBeenusedByid(personalUserCoupon.getOcId());
				}
			} else {
				return 101;
			}
		} catch (MalformedURLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return count;
	}

	@Override
	public OperatorEventDetails queryActivityUrl(String userId, String activityId) {
		OperatorEventDetails eventDetails = operatorEventDetailsRepository.findOne(activityId);
		int count = operatorActivityEnlistRepository.queryCountByUserIdAndActivity(userId, activityId);
		OperatorEventDetails operatorEventDetails = new OperatorEventDetails();
		if (eventDetails.getIsMoney() != null && eventDetails.getIsMoney() == 1) {// 收费
			if (count >= eventDetails.getUnitNum()) {
				operatorEventDetails.setId("-104");
				return operatorEventDetails;
			}
		}
		if (eventDetails.getIsMoney() != null && eventDetails.getIsMoney() == 0) {// 不收费
			if (count >= 1) {
				operatorEventDetails.setId("-104");
				return operatorEventDetails;
			}
		}
		operatorEventDetails.setId(activityId);
		operatorEventDetails.setEventUrl(eventDetails.getEventUrl());
		operatorEventDetails.setRegistrationFormDetails(eventDetails.getRegistrationFormDetails());
		return operatorEventDetails;
	}

}
